package ChatSystem;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * The TCPSender class is used to send a file to a remote ChatSystem user.
 *
 */
public class TCPSender {
	private Socket _socket;
	
	/**
	 * Initializes the sender.
	 */
	public TCPSender() {

	}
	
	/**
	 * Interrupts the transfer by closing the socket.
	 */
	public void cancel() {
		if(_socket != null) {
			try {
				_socket.close();
			} catch (IOException e) {}
		}
	}
	
	/**
	 * Sends a message over the network to the remote ChatSystem user.
	 * @param message The message to be sent.
	 */
	public void sendMessage(ChatMessage.ChatFileMessage message) {
		try {
			_socket = new Socket(message.getRecipient().getAddress(), message.getRecipient().getPort());

			message.setState(ChatMessage.ChatFileMessage.State.Transfer);
			FileInputStream fileStream = new FileInputStream(message.getPath());
			OutputStream out = _socket.getOutputStream();
			
			int count;
			byte[] buffer = new byte[1 << 20];
			while((count = fileStream.read(buffer)) > 0) {
			  out.write(buffer, 0, count);
			}
			
			fileStream.close();
			_socket.close();
			_socket = null;
			
			message.setState(ChatMessage.ChatFileMessage.State.Completed);
		}
		catch(Exception e) {
			message.setState(ChatMessage.ChatFileMessage.State.Error);
		}
	}	
}
